package com.example.demo.util;


import jdk.swing.interop.SwingInterOpUtils;
import lombok.Data;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;


@Component
@Data
@ConfigurationProperties(prefix = "wechat")
public class HttpUtil {

    private final static int TIMEOUT = 1000;
    private final static int TIMEOUT_MSEC = 5000;

    private   String REQUEST_URL; //请求地址
    private   String APPID ; //前面获取的appid
    private   String SECRET; //前面获取的小程序密钥，注意要和appid同属于一个项目
    private static final String GRANT_TYPE = "authorization_code";


    public  String doPost(String code) throws URISyntaxException, IOException {
        HttpClient httpClient = HttpClientBuilder.create().build();
        URIBuilder uriBuilder = new URIBuilder(REQUEST_URL);
        uriBuilder.setParameter("appid",APPID);
        uriBuilder.setParameter("secret",SECRET);
        uriBuilder.setParameter("js_code",code);
        uriBuilder.setParameter("grant_type",GRANT_TYPE);

        URI build = uriBuilder.build();
        HttpPost httpPost = new HttpPost(build);

        httpPost.setHeader("Content-type","application/json");

        HttpResponse execute = httpClient.execute(httpPost);
        HttpEntity entity = execute.getEntity();
        String string = EntityUtils.toString(entity);

        return string;
    }
}
